package handler

import (
	"context"
	"goods_srv/global"
	goods_pb "goods_srv/goodsPb"
	"goods_srv/model"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func (s *GoodsService) BannerList(ctx context.Context, req *goods_pb.Empty) (*goods_pb.BannerListResponse, error) {
	bannerListResponse := goods_pb.BannerListResponse{}
	var banners []model.Banner
	result := global.DB.Find(&banners)
	bannerListResponse.Total = int32(result.RowsAffected)

	var bannerReponses []*goods_pb.BannerResponse

	for _, banner := range banners {
		bannerReponses = append(bannerReponses, &goods_pb.BannerResponse{
			Id:    banner.ID,
			Image: banner.Image,
			Index: banner.Index,
			Url:   banner.Url,
		})
	}

	bannerListResponse.Data = bannerReponses
	return &bannerListResponse, nil
}

func (s *GoodsService) CreateBanner(ctx context.Context, req *goods_pb.BannerRequest) (*goods_pb.BannerResponse, error) {
	banner := model.Banner{}
	banner.Image = req.Image
	banner.Index = req.Index
	banner.Url = req.Url
	tx := global.DB.Save(&banner)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "添加轮播图失败")
	}
	return &goods_pb.BannerResponse{Id: banner.ID}, nil
}

func (s *GoodsService) DeleteBanner(ctx context.Context, req *goods_pb.BannerRequest) (*goods_pb.Empty, error) {
	if result := global.DB.Delete(&model.Banner{}, req.Id); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "轮播图不存在")
	}
	return &goods_pb.Empty{}, nil
}

func (s *GoodsService) UpdateBanner(ctx context.Context, req *goods_pb.BannerRequest) (*goods_pb.Empty, error) {
	var banner model.Banner
	if result := global.DB.First(&banner, req.Id); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "轮播图不存在")
	}
	if req.Url != "" {
		banner.Url = req.Url
	}
	if req.Image != "" {
		banner.Image = req.Image
	}
	if req.Index != 0 {
		banner.Index = req.Index
	}
	tx := global.DB.Save(&banner)

	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "修改轮播图信息失败")
	}
	return &goods_pb.Empty{}, nil
}
